import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings
# 获得token,解密token,拿到 payload 的信息
# payload ={'user_id':'', 'username':'', 'exp':''}
from rest_framework.response import Response

class JWTQueryParameAustentication(BaseAuthentication):
    def authenticate(self, request):
        SALT = settings.SECRET_KEY
        # 获取token的值
        token = request.query_params.get('token')
        payload = None
        msg = None


        try:
            payload = jwt.decode(token, key=SALT, verify=True)
        except jwt.exceptions.ExpiredSignature:
            msg = f"token失效{token}"
            raise AuthenticationFailed({'code':1003,'error':msg})
        except jwt.exceptions.DecodeError:
            msg = f"token认证失败{token}"
            raise AuthenticationFailed({'code': 1003, 'error': msg})
        except jwt.exceptions.InvalidTokenError:
            msg = f"非法token{token}"
            raise AuthenticationFailed({'code': 1003, 'error': msg})


        print(payload['user_id'],payload['username'])

        return (payload,token)
